const initState = window.sessionStorage.getItem('state') ?
    JSON.parse(window.sessionStorage.getItem('state')) :
    {
        shopList: [],
        cartList: []
    }

function reducer(state = initState, action) {

    switch (action.type) {
        case "SET_SHOP_LIST":
            state.shopList = action.data
            break;
        case "ADD_TO_CART":
            // 判断是不是第一次添加
            const ind = state.cartList.findIndex(item => item.id == action.data.id)
            if (ind !== -1) {
                state.cartList[ind].count += 1
            } else {
                state.cartList.push({
                    ...action.data,
                    count: 1,
                    checked: false
                })
            }
            console.log(state.cartList)
            break;
        case "SET_CART_COUNT":
            const ind2 = state.cartList.findIndex(item => item.id == action.data.id)
            state.cartList[ind2].count += action.data.num
            break;
        case "SET_CHECK":
            const ind3 = state.cartList.findIndex(item => item.id == action.data.id)
            state.cartList[ind3].checked = action.data.checked
            break;
        case "ALL_CHECK":
            state.cartList = state.cartList.map(item => {
                return { ...item, checked: action.data.checked }
            })
            break;
        case "DELETE_CART":
            const ind4 = state.cartList.findIndex(item => item.id == action.data.id)
            state.cartList.splice(ind4, 1)
            break;
        default:
            break;
    }
    window.sessionStorage.setItem('state', JSON.stringify(state))
    return JSON.parse(JSON.stringify(state))
}


export default reducer